package com.ews.onlineexchange.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.security.RolesAllowed;
import javax.enterprise.inject.Model;
import javax.inject.Inject;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;

import com.ews.onlineexchange.model.Bulletin;
import com.ews.onlineexchange.model.ServiceSupplier;
import com.ews.onlineexchange.model.Trade;
import com.ews.onlineexchange.model.TradeStatus;
import com.ews.onlineexchange.model.User;

/**
 * 中介机构用户查询本用户中标的所有交易清单
 * @author admin
 *
 */
@Model
@RolesAllowed(value = "supplier")
public class SupplierSuccessTradeList extends EntityQuery<Trade> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public SupplierSuccessTradeList() {
		super();
		setOrder("createDate DESC");
		
	}
	
	@Inject
	UserService userService;

	@Override
	protected List<Predicate> getRestrictions(CriteriaBuilder cb, Root<Trade> entity) {
		User loginedUser = userService.getLoginedUser();
		List<Predicate> restrictions = new ArrayList<Predicate>();
		restrictions.add(cb.isTrue(entity.<Boolean>get("apply")));
		
		Join<Trade, ServiceSupplier> supplier = entity.join("supplier");
		restrictions.add(cb.equal(supplier.get("username"), loginedUser.getUsername()));
		
		Join<Trade, Bulletin> bulletin = entity.join("bulletin");
		restrictions.add(cb.isTrue(bulletin.<Boolean>get("over")));		
		restrictions.add(cb.equal(bulletin.get("tradeStatus"), TradeStatus.Agreed));
		restrictions.add(cb.equal(bulletin.get("successTrade"), entity));
		//过滤已经取消的公告
		restrictions.add(cb.isFalse(bulletin.<Boolean>get("cancelled")));
		
		String projectName = (String)getParameterValues().get("projectName");
		if (!StringUtils.isBlank(projectName))
			restrictions.add(cb.like(bulletin.get("projectName"), getStringRestriction(projectName)));
		
		String serialNumber = (String)getParameterValues().get("serialNumber");
		if (!StringUtils.isBlank(serialNumber))
			restrictions.add(cb.like(bulletin.get("serialNumber"), getStringRestriction(serialNumber)));
		
		return restrictions;
	}
	
}
